package com.letao.server.service.impl;

import cn.hutool.core.lang.UUID;
import com.letao.server.dto.Result;
import com.letao.server.dto.UserInfoDTO;
import com.letao.server.entity.*;
import com.letao.server.service.*;
import com.letao.server.utils.OSSUtils;
import com.letao.server.utils.UserHolderUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

import static com.letao.server.constants.OSSConstants.*;


/**
 * 处理上传文件接口实现类
 */
@Service
@Slf4j
public class UploadServiceImpl implements IUploadService {

    @Resource
    private IUserService userService;

    @Resource
    private ISkuService skuService;

    @Resource
    private ISpuService spuService;

    @Resource
    private ISpuMediaService spuMediaService;

    @Resource
    private ISeckillService seckillService;

    @Resource
    private OSSUtils ossUtils;


    /**
     * 用于处理用户头像上传
     *
     * @param file 文件信息
     * @return 返回结果
     * @throws IOException 抛出的异常
     */
    @Override
    public Result updateUserImage(MultipartFile file) throws IOException {
        // 获取用户信息
        UserInfoDTO user = UserHolderUtils.getUser();
        UserInfo userInfo = userService.getById(user.getId());
        if (userInfo.getUserImage() != null && !userInfo.getUserImage().endsWith("default.jpg")) {
            ossUtils.delete(userInfo.getUserImage());
        }
        // 上传文件并获得文件URL
        String userImage = ossUtils.update(file, USER_IMAGE_USE, UUID.randomUUID().toString());
        // 更新用户信息
        userInfo.setUserImage(userImage);
        userService.updateById(userInfo);
        log.info("ID = {}的用户上传了头像, URL = {}", user.getId(), userImage);
        // 返回结果
        return Result.success(userImage);
    }

    /**
     * 上传sku图片
     *
     * @param file 图片文件
     * @param id   sku的Id
     * @return 返回的结果
     */
    @Override
    public Result updateSkuImage(MultipartFile file, Long id) throws IOException {
        SkuInfo sku = skuService.getById(id);
        if (sku == null) {
            return Result.fail("依赖不存在");
        }
        if (sku.getHasImage() != null && !sku.getHasImage().endsWith("default.jpg")) {
            ossUtils.delete(sku.getHasImage());
        }
        String skuImage = ossUtils.update(file, SKU_IMAGE_USE, UUID.randomUUID().toString());
        sku.setHasImage(skuImage);
        skuService.updateById(sku);
        return Result.success(skuImage);
    }

    /**
     * 上传spu描述图片或视频
     *
     * @param file 媒体文件
     * @param id   spu的Id
     * @return 返回的结果
     */
    @Override
    public Result updateSpuImage(MultipartFile file, Long id) throws IOException {
        SpuInfo spu = spuService.getById(id);
        if (spu == null) {
            return Result.fail("依赖不存在");
        }
        SpuMedia media = new SpuMedia();
        if (!file.getOriginalFilename().endsWith(".mp4")) {
            List<SpuMedia> list = spuMediaService.query().eq("spu_id", id).le("media_type", 1).list();
            if (list.size() >= 6) {
                return Result.fail("图片数过多");
            }
            if (list.isEmpty()) {
                media.setIsDefault(1);
            }
        }
        String spuImage = ossUtils.update(file, SPU_IMAGE_USE, UUID.randomUUID().toString());
        media.setSpuId(id);
        media.setMediaUrl(spuImage);
        if (media.getIsDefault() != null && media.getIsDefault().equals(1)) {
            spu.setSpuImage(spuImage);
            spuService.updateById(spu);
        }
        if (spuImage.endsWith("jpg")) {
            media.setMediaType(0);
        } else if (spuImage.endsWith("png")) {
            media.setMediaType(1);
        } else {
            SpuMedia video = spuMediaService.query().eq("spu_id", id).eq("media_type", 2).one();
            if (video != null) {
                media.setId(video.getId());
                ossUtils.delete(video.getMediaUrl());
            }
            media.setMediaType(2);
        }
        spuMediaService.saveOrUpdate(media);
        return Result.success(spuImage);
    }

    /**
     * 删除spu的媒体文件
     *
     * @param id 媒体文件的Id
     * @return 返回的结果
     */
    @Override
    public Result deleteSpuImage(Long id) {
        SpuMedia media = spuMediaService.getById(id);
        if (media == null) {
            return Result.fail("对象不存在");
        }
        if (media.getIsDefault() == 1) {
            return Result.fail("请先更换默认再删除");
        }
        ossUtils.delete(media.getMediaUrl());
        spuMediaService.removeById(id);
        return Result.success();
    }

    @Override
    public Result updateSeckillImage(MultipartFile file, Long id) throws IOException {
        SeckillInfo seckillInfo = seckillService.getById(id);
        if (seckillInfo == null) {
            return Result.fail("依赖不存在");
        }
        String url = ossUtils.update(file, SECKILL_IMAGE_USE, UUID.randomUUID().toString());
        seckillInfo.setSeckillImage(url);
        seckillService.updateById(seckillInfo);
        return Result.success(url);
    }


}
